package com.stone.config.exception;

import com.stone.bean.AppResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Objects;

/**
 * @author stone
 * @date 2022/3/3 9:31
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AppResponse exception(Exception e) {
        log.error("出现未知异常", e);
        return AppResponse.failed();
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public AppResponse businessException(BusinessException e) {
        log.info("业务拦截：{}", e.getMessage());
        if (Objects.nonNull(e.getAppResponse())) {
            return e.getAppResponse();
        }
        return AppResponse.intercept().setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public AppResponse methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuffer sb = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            sb.append(fieldError.getDefaultMessage());
            sb.append(";");
        }
        return AppResponse.intercept().setMessage(sb.toString());
    }
}

